<template>
  <div class="chart-container demo-spin-col">
    <h1 class="title">网络IO使用率</h1>
    <div :id="myChartThreeId" class="default-chart">
    </div>
    <div class="table-box">
      <table class="table table-0" v-show="!loadingShow">
        <tr>
          <th></th>
          <th></th>
          <th>最新Kbps</th>
          <th>最小Kbps</th>
          <th>平均Kbps</th>
          <th>最大Kbps</th>
        </tr>
      </table>
      <div class="seamless-box">
        <vue-seamless :data="tableArr" :class-option="classOption" v-show="isThisGuyShow">
          <table class="table">
            <tr v-for="(item,index) in tableArr" :key="index">
              <td><i class="spot" :style="{backgroundColor: item.color}"></i></td>
              <td>{{ item.title}}</td>
              <td>{{ item.newest}}</td>
              <td>{{ item.minimum}}</td>
              <td>{{ item.average}}</td>
              <td>{{ item.maxmum}}</td>
            </tr>
          </table>
        </vue-seamless>
      </div>
    </div>
    <Spin fix v-if="loadingShow">
      <Icon type="ios-loading" size=18 class="demo-spin-icon-load"></Icon>
      <div>Loading</div>
    </Spin>
  </div>
</template>

<script>
  let echarts = require('echarts/lib/echarts')
  import $ from "jquery";
  // import  from '../service/getColor.js'
  import {getColor,randomColors} from '../service/getColor.js'

  // 引入折线图
  require('echarts/lib/chart/line')
  // 引入提示框和title组件
  require('echarts/lib/component/tooltip')
  require('echarts/lib/component/title')
  import VueSeamless from 'vue-seamless-scroll'

  export default {
    name: "LineChartOne",
    props: [
      'threeId',
      'hostId',
      'currentIndex',
      'currentItemIndex'
    ],
    components: {
      VueSeamless
    },
    data() {
      return {
        myChartThreeId: 'myChartThree' + this.threeId,
        myChart: null,
        colors:[],
        tableArr: [],
        options:{
          title: {
            show: false,
            text: '内存使用率',
            x: 'left',
            y: 'top',

            textStyle: {
              color: '#ffffff',
              fontStyle: 'bold',
              fontSize: 20,
              verticalAlign: 'bottom'
            }
          },
          tooltip: {
            trigger: 'item',
            backgroundColor: 'rgba(0,0,0,0.4)',  //鼠标移动到图上面时，背景色
            padding: 2,     //定义内边距
          },
          xAxis: {
            type: 'category',
            splitNumber: 10,
            boundaryGap: true,
            data: [],
            //x轴的字体样式
            axisLabel: {
              rotate:45,
              show: true,
              textStyle: {
                color: '#08a9ae',
                fontSize: '12'
              }
            },
            // 控制网格线是否显示
            splitLine: {
              show: true,
              //  改变轴线颜色
              lineStyle: {
                color: ['#21475d'],
                width: 1,
                type: 'solid'
              }
            },
            // x轴的颜色和宽度
            axisLine: {
              show: true, //隐藏坐标轴
              lineStyle: {
                color: '#08a9ae',
                width: 1,   //这里是坐标轴的宽度,可以去掉
              }
            },
            // 去除坐标轴上的刻度线
            axisTick: {
              show: false
            }
          },
          yAxis: {
            type: 'value',
            name: 'Kbps',
            min:'0',
            max:function(value){
              return Math.ceil(value.max)
            },
            splitNumber: 5,
            axisLabel: {
              formatter: '{value}Kbps',
              show: true,
              textStyle: {
                color: '#263f6d'
              }
            },
            // y轴的颜色和宽度
            axisLine: {
              show: true,
              lineStyle: {
                color: '#263f6d',
                width: 1,   //这里是坐标轴的宽度
              }
            },
            splitLine: {
              show: false,
              //  改变轴线颜色
              lineStyle: {
                color: ['#21475d'],
                width: 1,
                type: 'solid'
              }
            },
          },
          grid: { //控制图的大小
            top: 10,
            x: 70,
            x2: 30,
            y2: 30
          },
          series: [
            {
              data:[],
              name:'Incoming',
              type: 'line',
              // smooth: true,
              radius: '0',
              center: ['0%', '0%'],
              symbolSize: 6,   //拐点圆的大小
              color: ['#CD2626'],  //折线条的颜色
              itemStyle: {
                normal: {
                  color: '#CD2626',
                  lineStyle: {
                    color: '#CD2626'
                  }
                }
              },
              areaStyle: {
                // 径向渐变，前三个参数分别是圆心 x, y 和半径，取值同线性渐变
                color: {
                  type: 'linear',
                  x: 0,
                  y: 0,
                  x2: 0,
                  y2: 1,
                  colorStops: [{
                    offset: 0, color: '#CD2626' // 0% 处的颜色
                  },{
                    offset: 0.5, color: '#CD3700' // 50% 处的颜色
                  }, {
                    offset: 1, color: '#CD5C5C' // 100% 处的颜色
                  }],
                  globalCoord: false // 缺省为 false
                }
              }
            },
            {
              data:[],
              name:'Outgoing',
              type: 'line',
              // smooth: true,
              radius: '0',
              center: ['0%', '0%'],
              symbolSize: 6,   //拐点圆的大小
              color: ['#00C5CD'],  //折线条的颜色
              itemStyle: {
                normal: {
                  color: '#00C5CD',
                  lineStyle: {
                    color: '#00C5CD'
                  }
                }
              },
              areaStyle: {
                // 径向渐变，前三个参数分别是圆心 x, y 和半径，取值同线性渐变
                color: {
                  type: 'linear',
                  x: 0,
                  y: 0,
                  x2: 0,
                  y2: 1,
                  colorStops: [{
                  offset: 0, color: '#19737a' // 0% 处的颜色
                }, {
                  offset: 1, color: '#151515' // 100% 处的颜色
                }],
                  globalCoord: false // 缺省为 false
                }
              }
            }
          ]
        },
        timer:null,
        showPointsNum:10,
        loadingShow:true
      }
    },
    mounted () {
      var _this=this;
      _this.getNetworkInfo();
      setTimeout(()=>{
        _this.drawLine();
      },0)

      this.timer=setInterval(()=>{
        console.log('1fenzhong')
        // this.getXdate()
        _this.getNetworkInfo()
      },60000)
    },
    // created() {
    //   // console.log('randomColors>>>>',randomColors)
    //   var _this=this;
    //   setTimeout(()=>{
    //     _this.drawLine();
    //     _this.getNetworkInfo();
    //   },0)

    //   this.timer=setInterval(()=>{
    //     // this.getXdate()
    //     _this.getNetworkInfo()
    //   },60000)
    // },
    destroyed () {
      clearInterval(this.timer);
    },
    methods: {
      drawLine() {
        // 绘制图表
        this.myChart = echarts.init(document.getElementById(this.myChartThreeId))
        this.myChart.setOption(this.options);
      },
      getDatas(obj){
        var _this=this;
        var data={
          "jsonrpc": "2.0",
          "method": "item.get",
          "params": {
              "output": "extend",
              "hostids": this.hostId,
              "search": obj,
              "sortfield": "name"
          },
          "auth": localStorage.getItem('auth'),
          "id": localStorage.getItem('currentId')
        }
        return new Promise((resolve,reject)=>{
          _this.$http.post('/zabbix/api_jsonrpc.php',data).then(
            res=>{
              resolve(res.result);
            },
            err=>{
              reject('获取数据失败，请检查网络状况，或稍后刷新页面..')
            }
          )
        })
      },
      async getNetworkInfo(){
        var _this=this;
        // console.time('testawait'+this.hostId);
        var res=await this.getDatas({"key_":"net"});
        // console.timeEnd('testawait'+this.hostId)
        if(_this.colors.length==0){
          for(let i=0;i<res.length;i++){
            _this.colors.push(getColor());
          }
        }
        _this.tableArr=[];
        // alert(1)
        var arrIn=[];
        var countIn=0;
        var arrOut=[];
        var countOut=0;
        //过滤 Incoming
        arrIn=res.filter(v=>{
          if(v.name.indexOf('Incoming network traffic on')!=-1)
          return v.name;
        })
        let InTotal=[]
        //计算 Incoming总值
        arrIn.forEach(v=>{
          countIn+=parseFloat(v.lastvalue)/1000;
          InTotal.push(parseFloat(v.lastvalue)/1000).toFixed(2);
        })
        let inmax=Math.max.apply(null, InTotal)
        let inmin=Math.min.apply(null, InTotal)
        let inavg=_this.getAvg(InTotal)
        //过滤 Outgoing
        arrOut=res.filter(v=>{
          if(v.name.indexOf('Outgoing network traffic on')!=-1)
          return v.name;
        });
        let OutTotal=[]
        //计算 Outgoing 总值
        arrOut.forEach(v=>{
          countOut+=parseFloat(v.lastvalue)/1000
          OutTotal.push(parseFloat(v.lastvalue)/1000).toFixed(2);
        })
        let outmax=Math.max.apply(null, OutTotal)
        let outmin=Math.min.apply(null, OutTotal)
        let outavg=_this.getAvg(OutTotal)


        _this.tableArr.push({
          title: 'Incoming total',
          newest: countIn.toFixed(2),
          color:'#CD2626',
          average:inavg.toFixed(2),
          minimum:inmin.toFixed(2),
          maxmum:inmax.toFixed(2),
        })
        _this.tableArr.push({
          title: 'Outgoing total',
          newest: countOut.toFixed(2),
          color:'#00C5CD',
          average:outavg.toFixed(2),
          minimum:outmin.toFixed(2),
          maxmum:outmax.toFixed(2),
        })
        //push Incoming
        if(_this.options.series[0].data.length<_this.showPointsNum){
          _this.options.series[0].data.push(countIn.toFixed(2))
        }else{
          _this.options.series[0].data.shift();
          _this.options.series[0].data.push(countIn.toFixed(2));
        }
        //push Outgoing
        if(_this.options.series[1].data.length<_this.showPointsNum){
          _this.options.series[1].data.push(countOut.toFixed(2))
        }else{
          _this.options.series[1].data.shift();
          _this.options.series[1].data.push(countOut.toFixed(2));
        }

        //获取数组内最大值 设置y轴最大值
        var max = _this.options.series[1].data.sort().reverse()[0];
        // console.log('******----->',max)
        _this.options.yAxis.max({min:'0',max:parseInt(max)});

        //push当前时间
        var date=new Date()
        var h=date.getHours();
        var m=date.getMinutes();
        if(m<10){
          m='0'+m;
        }
        var time=h+":"+m;
        if(_this.options.xAxis.data.length<_this.showPointsNum){
          _this.options.xAxis.data.push(time)
        }else{
          _this.options.xAxis.data.shift();
          _this.options.xAxis.data.push(time)
        }

        let TotalData=[];//保存所有的数据，用来求最大最小平均值
        res.forEach((v,k )=> {
          TotalData.push(parseFloat(v.lastvalue)/1000);
          let max=Math.max.apply(null, TotalData)
          let min=Math.min.apply(null, TotalData)
          let avg=_this.getAvg(TotalData)
          let key=v.key_.match(/\[(\S*)]/)[1];
          let name=v.name.replace(/\$1/g, key);
          name=name.split(' ');
          // console.log('key,name',key,name);
          var theName='';
          theName=name[0]+' on '+name[name.length-1]
          _this.tableArr.push(
            {
              title: theName+' [平均]',
              newest: (parseFloat(v.lastvalue)/1000).toFixed(2),
              color:_this.colors[k],
              average:avg.toFixed(2),
              minimum:min.toFixed(2),
              maxmum:max.toFixed(2),
            }
          );
        });
        _this.myChart.setOption(_this.options);
        this.loadingShow=false;
      },
      getAvg(arr){
        let sum = 0;
        for(var i=0;i<arr.length;i++){
          sum += arr[i];
        }
        let avg = sum/arr.length;
        return avg;
      }
    },
    computed: {
      classOption: function () {
        return {
          step: 0.2,
          limitMoveNum: 10
        }
      },
      isThisGuyShow:function(){
        return this.currentIndex==this.currentItemIndex
      }
    },
  }
</script>

<style scoped lang="scss">
  .chart-container {
    color: #ffffff;
    width: 472px;
    height: 336px;
    border: 28px solid;
    border-top: 5px solid;
    border-right: 5px solid;
    /*border-left: 5px solid;*/
    /*border-bottom: 20px solid;*/
    background: transparent;
    border-image: url('../assets/images/32.png') 28 fill repeat;
    position: relative;
    margin-top: 60px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    align-items: center;
    overflow: hidden;


    .title {
      color: #fff;
      width: 20px;
      font-size: 16px;
      word-wrap: break-word;
      position: absolute;
      right: 10px;
      top: 10px;
    }

    .default-chart {
      width: 100%;
      height:100%;
      flex: 1;
      padding-right: 20px;
      /*position: absolute;*/
      /*right: 30px;*/
      /*top: 0;*/
    }

    .table-box {
      table {
        height: 166px;
        width: 100%;;
        // position: absolute;
        // top: 178px;
        // right: 0;
        color: #08a9ae;
        text-align: center;
        line-height: 12px;

        &.table-0 {
          height: 20px;
          /*position: fixed;*/
        }

        tr {
          th, td {
            width: 60px;
            text-align: center;
            vertical-align: top;
            display: inline-block;
            word-wrap: break-word;
            word-break: normal;

            &:first-child {
              width: 14px;
            }

            &:nth-child(2) {
              width: 150px;
              text-align: left;
            }

            .spot {
              width: 9px;
              height: 9px;
              display: inline-block;
              background: #08a9ae;
              margin-right: 5px;
            }
          }
        }
      }

      .seamless-box {
        height: 146px;
        overflow: hidden;
      }
    }
  }
  /*加载中的作用范围*/
.demo-spin-col{
  position: relative;
}
.ivu-spin-fix{
  background-color: rgba(0, 0, 0, .2);
}
.demo-spin-icon-load{
  animation: ani-demo-spin 1s linear infinite;
}
</style>
